package cn.edu.heuet.bnve.activity.SettingActivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.xuexiang.xui.adapter.simple.AdapterItem;
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet;
import com.xuexiang.xui.widget.grouplist.XUICommonListItemView;
import com.xuexiang.xui.widget.grouplist.XUIGroupListView;
import com.xuexiang.xui.widget.imageview.RadiusImageView;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;
import com.xuexiang.xui.widget.popupwindow.popup.XUISimplePopup;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.edu.heuet.bnve.R;
import cn.edu.heuet.bnve.activity.ScheduleActivity.SetLocalActivity;
import cn.edu.heuet.bnve.databinding.ActivityInforSettingBinding;
import cn.edu.heuet.bnve.utils.DialogUtil;
import cn.edu.heuet.bnve.utils.LQRPhotoSelectUtils;
import cn.edu.heuet.bnve.utils.SharepreferencesUtilSystemSettings;
import cn.edu.heuet.bnve.utils.ToastUtil;


public class InforSettingActivity extends AppCompatActivity {

    private ActivityInforSettingBinding binding;
    private XUIGroupListView mGroupListView;
    private Toolbar toolbar;
    private XUISimplePopup mMenuPopup;

    private RadiusImageView head;

    private TimePickerView mDatePicker;

    private XUICommonListItemView item4Location;


    LQRPhotoSelectUtils mLqrPhotoSelectUtils;
    private static final int REQUEST_CODE = 0x001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_infor_setting);
        initData();
        initView();
        initEvent();
    }

    public static void show(Context context) {
        context.startActivity(new Intent(context, InforSettingActivity.class));
    }


    public void initData(){

        initPhotoSelecter();
        initMenuPopup();
    }

    public void initView(){
        mGroupListView = binding.inforGroupListView;
        initGroupListView();

        toolbar=binding.toolbarContainer.toolbar;
        setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.setting);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        head = binding.headImg;
        String headURI = SharepreferencesUtilSystemSettings.getValue(this,"infor_head",null);
        if (headURI!=null) {
            head.setImageURI(Uri.fromFile(new File(headURI)));
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void initEvent(){

        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMenuPopup.showDown(view);
            }
        });

    }
    private void initGroupListView() {

        XUICommonListItemView item1 = mGroupListView.createItemView(
                "昵称");
        item1.setTag(1);
        item1.setOrientation(XUICommonListItemView.HORIZONTAL);
        item1.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item1.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_name","无"));


        XUICommonListItemView item2 = mGroupListView.createItemView(
                "性别");
        item2.setTag(2);
        item2.setOrientation(XUICommonListItemView.HORIZONTAL);
        item2.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        String[] item2Values ={"男","女","未知"};
        switch (SharepreferencesUtilSystemSettings.getValue(this,"infor_gender",2)){
            case 0:
                item2.setDetailText(item2Values[0]);
                break;
            case 1:
                item2.setDetailText(item2Values[1]);
                break;
            case 2:
                item2.setDetailText(item2Values[2]);
                break;
        }

        XUICommonListItemView item3 = mGroupListView.createItemView(
                "生日");
        item3.setTag(3);
        item3.setOrientation(XUICommonListItemView.HORIZONTAL);
        item3.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item3.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_born_date","无"));

        XUICommonListItemView item4 = mGroupListView.createItemView(
                "所在地");
        item4.setTag(4);
        item4.setOrientation(XUICommonListItemView.HORIZONTAL);
        item4.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item4.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_location","无"));
        item4Location = item4;

        XUICommonListItemView item5 = mGroupListView.createItemView(
                "学校");
        item5.setTag(5);
        item5.setOrientation(XUICommonListItemView.HORIZONTAL);
        item5.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item5.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_school","无"));


        XUICommonListItemView item6 = mGroupListView.createItemView(
                "学院");
        item6.setTag(6);
        item6.setOrientation(XUICommonListItemView.HORIZONTAL);
        item6.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item6.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_faculty","无"));

        XUICommonListItemView item7 = mGroupListView.createItemView(
                "学号");
        item7.setTag(7);
        item7.setOrientation(XUICommonListItemView.HORIZONTAL);
        item7.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        item7.setDetailText(SharepreferencesUtilSystemSettings.getValue(this,"infor_number","无"));


        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof XUICommonListItemView) {
                    int tagValue = (Integer) ((XUICommonListItemView) v).getTag();
                    switch (tagValue){
                        case 1:
                            DialogUtil.showInputDialog(InforSettingActivity.this,"请输入昵称",item1,8,"infor_name");
                            break;
                        case 2:
                            new BottomSheet.BottomListSheetBuilder(InforSettingActivity.this)
                                    .setTitle("选择性别")
                                    .addItem("男")
                                    .addItem("女")
                                    .addItem("未知")
                                    .setIsCenter(true)
                                    .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                                        dialog.dismiss();
                                        SharepreferencesUtilSystemSettings.putValue(InforSettingActivity.this,"infor_gender",position);
                                        item2.setDetailText(item2Values[position]);
                                    })
                                    .build()
                                    .show();
                            break;
                        case 3:
                            showDatePicker(item3);
                            break;

                        case 4:
                            startActivityForResult(new Intent(InforSettingActivity.this, SetLocalActivity.class), 2);
                            break;
                        case 5:
                            DialogUtil.showInputDialog(InforSettingActivity.this,"请输入学校",item5,15,"infor_school");
                            break;
                        case 6:
                            DialogUtil.showInputDialog(InforSettingActivity.this,"请输入学院",item6,10,"infor_faculty");
                            break;
                        case 7:
                            DialogUtil.showInputDialog(InforSettingActivity.this,"请输入学号",item7,10,"infor_number");
                            break;
                        default:
                            break;
                    }

                }
            }
        };

//        int size = DensityUtils.dp2px(this, 23);
        XUIGroupListView.newSection(this)
                .setTitle("个人信息")
                .addItemView(item1, onClickListener)
                .addItemView(item2, onClickListener)
                .addItemView(item3, onClickListener)
                .addItemView(item4, onClickListener)
                .addTo(mGroupListView);

        XUIGroupListView.newSection(this)
                .setTitle("学籍信息")
                .addItemView(item5, onClickListener)
                .addItemView(item6, onClickListener)
                .addItemView(item7, onClickListener)
                .addTo(mGroupListView);

    }

    private void initMenuPopup() {
        String[] values = {"拍照","从相册选择"};
        mMenuPopup = new XUISimplePopup(this, values).create(new XUISimplePopup.OnPopupItemClickListener() {
            @Override
            public void onItemClick(XUISimpleAdapter adapter, AdapterItem item, int position) {
                if(position==1){
                    //选择照片
                    mLqrPhotoSelectUtils.selectPhoto();
                }
                else if(position==0){
                    //拍照
                    mLqrPhotoSelectUtils.takePhoto();
                }
            }
        });
    }

    public void initPhotoSelecter(){
        //初始化
        //创建LQRPhotoSelectUtils（一个Activity对应一个LQRPhotoSelectUtils）
        mLqrPhotoSelectUtils = new LQRPhotoSelectUtils(this, new LQRPhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri) {
                //当拍照或从图库选取图片成功后回调
//                mTvPath.setText(outputFile.getAbsolutePath());//显示图片路径
//                mTvUri.setText(outputUri.toString());//显示图片uri
//                //System.out.println(outputUri.toString());
//                Glide.with(InforModifyActivity.this).load(outputUri).into(mIvPic);//使用Glide进行图片展示
                ToastUtil.showMsg(InforSettingActivity.this, "选择完成");
                String headSource = outputFile.getAbsolutePath();
                head.setImageURI(Uri.fromFile(new File(headSource)));
                SharepreferencesUtilSystemSettings.putValue(InforSettingActivity.this,"infor_head",headSource);

            }
        }, true);//是否裁剪。true裁剪，false不裁剪

        //检查权限
        if (ContextCompat.checkSelfPermission(InforSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED||
                ContextCompat.checkSelfPermission(InforSettingActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED||
                ContextCompat.checkSelfPermission(InforSettingActivity.this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(InforSettingActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_CODE);
        }else{
            ToastUtil.showMsg(InforSettingActivity.this, "已经获得了所有权限");
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        if (requestCode == 2) {
            if (resultCode == 2) {
                if (data != null) {
                    String local = data.getStringExtra("local");
                    item4Location.setDetailText(local);
                    SharepreferencesUtilSystemSettings.putValue(this,"infor_location",local);
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
        //在Activity中的onActivityResult()方法里与LQRPhotoSelectUtils关联
        mLqrPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
    }



    /**
     * 获取头像保存位置
     * @return
     */
    public  String getHeadPath(String user_id) {
        String mFile = null;
        if (mFile == null) {
            //mFile = Environment.getExternalStorageDirectory()+ "/MicroHabit/"+user_id+".jpg";
            //String path = Environment.getExternalStorageDirectory() + "/MicroHabit";
            if (getApplicationContext() == null) {
                return "";
            }
            String path = getApplicationContext().getExternalFilesDir(null) + "/infor";
            mFile = getApplicationContext().getExternalFilesDir(null) + "/infor/head.jpg";
            //storage/emulated/0/Android/data/com.microhabit/files/MicroHabit/111.jpg
            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
        }
        return mFile;
    }

    private void showDatePicker(XUICommonListItemView itemView) {
        if (mDatePicker == null) {
            mDatePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelected(Date date, View v) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    itemView.setDetailText(sdf.format(date));
                    SharepreferencesUtilSystemSettings.putValue(InforSettingActivity.this,"infor_born_date",sdf.format(date));
                }
            })
                    .setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
                    .setTitleText("日期选择")
                    .build();
        }
        mDatePicker.show();
    }
}